﻿var Account = new function () {
    'use strict';
    this.onLogin = function () {
        var userName = $('input[name="userName"]').val();
        if (!userName) {
            alert('请输入用户名!');
            return;
        }

        var password = $(':password').val();
        if (!password) {
            alert('请输入密码!');
            return;
        }

        //password = sha256(password);
        var $autoLogin = $('input[name="autoLogin"]');
        $autoLogin.val($autoLogin.prop('checked'));
        var returnUrl = Account.getQueryString('ReturnUrl');
        if (returnUrl) {
            $('input[name="returnUrl"]').val(returnUrl);
        }

        $('.login form').submit();
    }

    this.onLoginSuccess = function (el, data) {
        if (data) {
            app.cache.global.set('user', data);
        }

        location.href = "/Home/Index";
    }

    this.onResetPassword = function () {
        location.href = "/Account/Login";
    }

    this.onLogout = function () {
        $.ajax({
            type: 'POST',
            url: '/Account/Logout',
            dataType: 'json',
            contentType: 'application/ json',
            success: () => {
                localStorage.clear();
                location.href = "/Account/Login"
            },
            error: err => {
                console.log(err);
            },
            complete: () => {
                localStorage.clear();
                location.href = "/Account/Login"
            }
        });
    };

    this.getQueryString = function (key) {
        var queryString = location.href.match(new RegExp("[\?\&][^\?\&]+=[^\?\&]+", "g"));
        if (queryString && queryString instanceof Array && queryString.length > 0) {
            for (var i = 0; i < queryString.length; i++) {
                var cur = queryString[i];
                cur = cur.substring(1);
                if (cur) {
                    var index = cur.indexOf('=');
                    if (index > 0) {
                        var name = cur.substring(0, index);
                        if (name == key) {
                            return cur.substring(index + 1, cur.length);
                        }
                    }
                }
            }
        }

        return undefined;
    };
}